package com.ht.pms.core.dao.sql;

import com.ht.pms.core.dto.dict.DictParamsDto;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Component
public class SqlAssembleTemp {

    public String assembleQuery(List<DictParamsDto> dictList,Map<String,Object> whereMap){
        List<String> tables = new ArrayList<>();
        StringBuilder sb = new StringBuilder();
        StringBuilder param = new StringBuilder();

        sb.append("select ");
        for (DictParamsDto dictParamsDto : dictList) {
            String tableName = dictParamsDto.getDictTableName();
            String columnName = dictParamsDto.getDictColumn();
            String dictCode = dictParamsDto.getDictCode();
            param.append(tableName+"."+columnName + " AS " + dictCode + ",");
            if (!tables.contains(tableName)) {
                tables.add(tableName);
            }
        }
        String queryParam = param.toString();
        String querySub = null;
        if (queryParam.endsWith(",")) {
            querySub = queryParam.substring(0, queryParam.length() - 1);
            sb.append(querySub);
        }
        if (!CollectionUtils.isEmpty(tables)) {
            StringBuilder table = new StringBuilder();
            table.append(" from ");
            for (int i = 0; i < tables.size(); i++) {

                if (i == 0) {
                    table.append(tables.get(i));
//                    table.append(" inner join t_dict_record_base as base on "+tables.get(i)+".batch_code=base.batch_code and "+tables.get(i)+".job_code=base.job_code ");
                } else if (i + 1 <= tables.size()) {
                    table.append(" left join " + tables.get(i)+" on "+tables.get(i-1)+".batch_code="+tables.get(i)+".batch_code and "+tables.get(i-1)+".job_code="+tables.get(i)+".job_code");
                }
            }
            sb.append(table);
        }

        StringBuilder where = new StringBuilder();
        where.append(" where 1=1");

        for (String key : whereMap.keySet()) {
            if(whereMap.get(key) instanceof Integer){
                where.append(" and "+tables.get(0)+"."+key+"="+whereMap.get(key));

            }else if(whereMap.get(key) instanceof String){
                where.append(" and "+tables.get(0)+"."+key+"='"+whereMap.get(key)+"'");
            }
        }
        sb.append(where);
        return sb.toString();
    }

}
